import { ref, reactive, onMounted } from 'vue';
import { emitter } from "@/utils/mitt";
import { useRoute } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import {
  ProActivityGetActivity,
  ProActivityGetActivityTypes,
  ProActivityInsertActivity,
  ProActivityStartSuspend
} from "@/api/stu/InsuranceData";
import { SpliceDate } from "@/utils/public/method"
import { type PaginationProps } from "@pureadmin/table";
import qs from 'qs';
export function useNewActivity() {
  const route = useRoute();
  const loading = ref(false)
  const dataList = ref([]);
  const RefFom = ref()
  const DialogVisible = ref(false);
  const btnloading = ref<boolean>(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [5, 10, 30],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "客群名称",
      prop: "customerName",
    },
    {
      label: "活动名称",
      prop: "aName",
    }, {
      label: "发送时间",
      prop: "sendTime",
      cellRenderer: ({ row }) => (
        <span>{SpliceDate(row.sendTime)}</span>
      )
    },
    {
      label: "活动状态",
      prop: "status",
      cellRenderer: ({ row }) => (
        <span>
          {
            row.status == '0' ? "待启动" :
              row.status == '1' ? "已启动" : '已暂停'
          }
        </span>
      )

    }, {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const CustomerList = ref([])
  const MovementList = ref([]);
  const form = reactive<any>({
    name: "",
    date: "",
    customer: "",
    movement: "",
    sendcontent: ""
  })

  const rules = {
    name: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value.length < 4) {
            return callback(new Error('活动名称4-15个汉字，不可重复'))
          } else {
            return callback()
          }
        }, trigger: ['change', 'blur']
      }
      // { required: true, message: "请输入活动名称", trigger: ["blur", "change"] }
    ],
    date: [{ required: true, message: "请输入活动时间", trigger: ["blur", "change"] }],
    customer: [{ required: true, message: "请选择客户群体", trigger: ["blur", "change"] }],
    movement: [{ required: true, message: "请选择触发动作", trigger: ["blur", "change"] }],
    sendcontent: [{ required: true, message: "请输入发送内容", trigger: ["blur", "change"] }],
    addevents: [{ required: true, message: "请选择条件类型", trigger: ["blur", "change"] }],
  };

  // 保存新建活动
  function sbutim_from(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
        aName: form.name,  //活动名称
        tiggerAction: form.movement,  //触发动作
        sendContent: form.sendcontent,  //发送内容
        sendTime: form.date,   //发送时间
        customer: form.customer?.id,//客户群体
        customerName: form.customer?.name
      };
      btnloading.value = true
      const res = await ProActivityInsertActivity(data);
      if (res.success) {
        ElMessage.success(res.msg);
        GetDataList()
        close_from(row)
        btnloading.value = false;
      } else {
        ElMessage.error(res.msg)
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    })
  }

  // 启动
  async function ViewOpenOrStop(row) {
    // const data = {...row,...{}}
    const res = await ProActivityStartSuspend(row)
    if (res.success) {
      ElMessage.success(res.msg)
      GetDataList()
    } else {
      ElMessage.error(res.msg)
    }
    console.log("stop-open", res)
  }

  // 清空表单
  function close_from(row: FormInstance | undefined) {
    row.resetFields();
    DialogVisible.value = false;
  }

  function handleSizeChange(val) {
    GetDataList()
  }
  function handleCurrentChange(val) {
    GetDataList()
  }

  async function GetActivityList() {
    const data = qs.stringify({
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    });
    const res = await ProActivityGetActivityTypes(data);
    if (res.success) {
      MovementList.value = res.data.tigger;
      CustomerList.value = res.data.pproCustomHosts;
    } else {
      ElMessage.error(res.msg);
    }
  }

  async function GetDataList() {
    const data = {
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize,
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    };
    const res = await ProActivityGetActivity(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount
    } else {
      ElMessage.error(res.msg);
    }
  }

  onMounted(() => {
    GetDataList()
    GetActivityList()
  })

  return {
    form,
    rules,
    RefFom,
    loading,
    columns,
    dataList,
    btnloading,
    pagination,
    CustomerList,
    MovementList,
    DialogVisible,
    ViewOpenOrStop,
    close_from,
    sbutim_from,
    handleSizeChange,
    handleCurrentChange
  }
}
